package controller;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import model.ChatMessage;
import model.ChatModel;
import view.ChatComponent;

public class ChatController {
	final private ChatModel model;
	final private ChatComponent view;
	public ChatController(ChatModel tmodel, ChatComponent tview) {
		this.model = tmodel;
		this.view = tview;
		view.getInputField().addKeyListener(new KeyListener() {

			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode()==KeyEvent.VK_ENTER) {
					submitMessage();
				}
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}
	
	/** Submits the contents of the input field into the server. */
	public void submitMessage() {
		ClientHandler.chatMessage(MetaDeckController.getInstance().getMyName(), view.getInputField().getText());
		view.getInputField().setText("");
	}
	/** Accepts a new chat message from the server */
	public void acceptMessage(String sender, String message) {
		model.addMessage(new ChatMessage(sender, message));
		view.updateDisplay();
	}
}
